package com.example.custom.rpc.proxy;


import com.example.custom.rpc.common.URL;
import com.example.custom.rpc.loadbalance.LoadBalance;
import com.example.custom.rpc.protocol.HttpClient;
import com.example.custom.rpc.common.Invocation;
import com.example.custom.rpc.register.MapRemoteRegister;

import java.lang.reflect.Proxy;
import java.util.List;

/**
 * @author liyuncong
 * @version 1.0
 * @file ProxyFactory
 * @brief ProxyFactory
 * @details ProxyFactory
 * @date 2022-11-03
 *
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                     NAME               DESCRIPTION
 * 2022-11-03               liyuncong          Created
 */
public class ProxyFactory {

    public static <T> T getProxy(Class interfaceClass) {

        final Object instance = Proxy.newProxyInstance(
            interfaceClass.getClassLoader(),
            new Class[]{interfaceClass},
            (proxy, method, args) -> {

                Invocation invocation = new Invocation(
                    interfaceClass.getName(),
                    method.getName(),
                    method.getParameterTypes(),
                    args
                );
                HttpClient httpClient = new HttpClient();

                // 服务发现
                List<URL> urls = MapRemoteRegister.get(interfaceClass.getName());
                final URL random = LoadBalance.random(urls);

                return httpClient.send(random.getHostname(), random.getPort(), invocation);
            });

        return (T) instance;
    }
}
